'''
Created on Sep 3, 2011

@author: david
'''

from app.G6.actions import G6Action

class Logon(G6Action):
    """
    Default Action 
    spawns index.gen
    """
    def execute(self):
        import logging
        from app.G6.agents import AccountAgent 
        from app.G6.agents import AccountException
        import json
        import logging
        
        aa = AccountAgent()
        
        req = self.request
        rslt = "200"
        nxtPage = "/G6/blogger.gen"
        req.setAttribute('chunk','1')
        msg = 'OK'
        acct = None
        
        # check credentials...
        try:
            uid = req.getParameter("uid")
            pwd = req.getParameter("pwd")
            
            logging.debug("~~ %s | %s" % (uid,pwd))
            
            acct = aa.fetch(uid, pwd).toJSON()
            
            if not acct:
                raise AccountException("Access Denied: Invalid Credentials for %d" % uid)

            req.session['g6acct'] = acct
        
            logging.info("++ Login: %s" % uid)
        
        except Exception, ex:
                # invalid!!!!
                rslt = "401::%s" % str(ex)
                nxtPage = "NO_CHANGE"
                logging.exception("!! Access Exception:")
                msg = "Access Denied (Invalid Credentials)"
                
        # prep the rtn
        del(acct["pwd"]) 
        rv = { "results": rslt, "next": nxtPage, "messsage": msg, "acct": acct }
        logging.debug("~~ Returning: %s" % str(rv))
        
        return self.JSONOutput(json.dumps(rv))
    